package com.dgut.cbd.controller;

import com.dgut.cbd.data.DataContainer;
import com.dgut.cbd.entity.DataModel;
import com.dgut.cbd.result.RO;
import com.dgut.cbd.service.MainService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Collectors;

/**
 * @Program: exp3
 * @Description:
 * @Author: cbd
 * @Create: 2021-05-20
 * @Version: 1.0.0
 **/


@RequestMapping("/api")
@RestController
@CrossOrigin
@Slf4j(topic = "myLog")
public class MainController {

    @Autowired
    ReadWriteLock rwlock;

    @Autowired
    MainService mainService;

    @RequestMapping("/{country}")
    public RO getCountryState(@PathVariable String country) {
        rwlock.readLock().lock();
        try {
            country = country.toLowerCase();
            List<String> collect = mainService.searchState(country);
            return RO.success(collect);
        }finally {
            rwlock.readLock().unlock();
        }
    }


    @RequestMapping("/{country}/{state}")
    public RO getDataModel(@PathVariable String country, @PathVariable String state,
                           @RequestBody Map<String, Date> map) throws JsonProcessingException {

        rwlock.readLock().lock();
        try {
            country = country.toLowerCase();
            state = state.toLowerCase();
            Date startDate = map.get("startDate");
            Date endDate = map.get("endDate");

            List<DataModel> dateModels = mainService.getDateModels(country, state, startDate, endDate);
            return RO.success(dateModels);
        }finally {
            rwlock.readLock().unlock();
        }
    }


}
